<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('reportQuery.supplier')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('reportQuery.selectCustomer')" showSearch
                    :dropdownMatchSelectWidth="false" v-decorator="[ 'organId', validatorRules.organId ]" optionFilterProp="children">
                    <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
          </a-col> -->
          
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'billNo' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          
          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="accountTable.loading"
          :columns="accountTable.columns"
          :dataSource="accountTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="false"
          @inputPurchaseValueChange="onChange"
          @valueChange="onValueChange">   
          <template #buttonBefore>
          <a-row :gutter="24" style="float:left;padding-bottom: 5px;" data-step="4"
              :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
            
            <a-col :md="6" :sm="24">
              <a-button type="primary" icon="plus" @click="AddDaily()">{{ $t('reportQuery.getDailyDetails') }}</a-button>
            </a-col>
          </a-row>
          </template>     
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>

        <a-table class="total__table" ref="table"
            bordered
            rowKey="id"
            width="300px"
            size="small"
            :pagination="false"
             :dataSource="totalTable.dataSource" 
             :columns="totalTable.columns" />
        <a-row class="form-row" :gutter="24" >
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.checkIncome')">
              <a-input :placeholder="$t('financialManagement.checkIncome')" v-decorator.trim="[ 'invoiceTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.cashIncome')">
              <a-input :placeholder="$t('financialManagement.cashIncome')" v-decorator.trim="[ 'cashTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.bank')">
              <a-input :placeholder="$t('otherJS.bank')" v-decorator.trim="[ 'bankTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <!-- 10000 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.boxAmount')">
              <a-input :placeholder="$t('financialManagement.boxAmount')" v-decorator.trim="[ 'retainedAmount' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.deductAmount')">
              <a-input :placeholder="$t('financialManagement.deductAmount')" v-decorator.trim="[ 'deductAmountTotal' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup,getDetailListByTime } from '@/api/api'
  import PersonModal from '../../system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import {randomUUID} from '@/utils/util';
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import moment from 'moment';
  export default {
    name: "DailyReconciliationModal",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        supList: [],
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        prefixNo: 'MRDZB',
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('financialManagement.lessee'),key: 'username', width: '10%', type: FormTypes.input,readonly:true,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: '',key: 'lessee', width: '16%', type: FormTypes.hidden,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.device'),key: 'device', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.cashAmount'),key: 'cashAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'KINA EFS/' +this.$t('otherJS.bank'),key: 'bankAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: `CHQ(${this.$t('financialManagement.CHQ')})`,key: 'invoiceAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'OTHERS',key: 'specialAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.presenterMoney'),key: 'giftAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.discountWhenSpendingEnough'),key: 'discountAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.breakageAmount'),key: 'breakageAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'G/TOTAL',key: 'subTotal', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'Reading',key: 'readingTotal', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: 'g.ttl',key: 'ttl', width: '8%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.boxAmount'),key: 'boxAmount', width: '8%', type: FormTypes.input,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.deductAmount'),key: 'deductAmount', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('financialManagement.differenceAmount'),key: 'difference', width: '8%', type: FormTypes.normal,placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          ]
        }, 
        totalTable:{
          loading:false,
          dataSource:[],
          columns:[
          { title: this.$t('financialManagement.lessee'),dataIndex: 'loginName', width: '8%'},
          
          { title: 'S/Total',dataIndex: 'totalAmount', width: '8%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
          ]
        },
        confirmLoading: false,
        validatorRules:{
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleasePaymentMember')+'!' }
            ]
          },
          handsPersonId:{
            rules: [
              { required: true, message:this.$t('popup.pleaseSelectPersonnel')+'!'}
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          }
        },
        url: {
          add: '/dailyHead/addDailyHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/dailyItem/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      clearData(){
        this.accountTable.dataSource = []
        this.totalTable.dataSource = []
      },
      async AddDaily(){
        let time = moment(new Date()).format('YYYY-MM-DD')
        const res = await getDetailListByTime({time:time})
        this.accountTable.dataSource = []
        if(res.code == 200){
          let arr = res.data.rows || []
          this.accountTable.dataSource.splice(0,0,...arr)
          this.updataForm(this.accountTable.dataSource)
          // 计算所有
          this.countTotal(this.accountTable.dataSource)

        }else{
          this.$message.error(res.msg || res.data)
        }
      },
      countTotal(array){
        const arr = [...new Set(this.accountTable.dataSource.map(v=>v.lessee))]
        this.totalTable.dataSource = arr.map(v=>{
            let obj = {}
            obj.totalAmount = array.filter(val=>val.lessee === v).reduce((s,c)=>{
              return s += +c.readingTotal || 0
            },0)
            obj.lessee = v
            obj.username = array.find(val=>val.lessee === v).username
            return obj
        })
        
      },
      updataForm(array){
        const table = this.$refs[this.refKeys[0]]
        let invoiceTotal = 0,cashTotal = 0,bankTotal = 0,retainedAmount = 0,deductAmountTotal =0
        array.forEach(object => {
            for (const key in object) {
              if (Object.hasOwnProperty.call(object, key)) {
                if(object[key] === null){
                  if(key.indexOf('Amount')>-1 || key.indexOf('Total')>-1 || key==='difference' || key === 'ttl'){
                    object[key] = 0
                  }
                }
              }
            }
            // 3+4+5-6-7-8-9 数字代表列号
            object.readingTotal = object.cashAmount + object.bankAmount + object.invoiceAmount - object.specialAmount - object.breakageAmount
            // object.readingTotal = object.cashAmount + object.bankAmount + object.invoiceAmount - object.specialAmount - object.discountAmount - object.breakageAmount - object.giftAmount
            // 11-13
            object.deductAmount = object.readingTotal - object.boxAmount
            object.difference = object.subTotal - object.deductAmount
            object.id = randomUUID()
            // 支票收入10000
            invoiceTotal +=  +object.invoiceAmount
            // 现金收入
            cashTotal +=  +object.cashAmount
            // 银行收入
            bankTotal +=  +object.bankAmount
            // 底箱留存金额
            retainedAmount +=  +object.boxAmount
            // 扣除后总额
            deductAmountTotal += +object.deductAmount
          });
          console.log('invoiceTotal :>> ', invoiceTotal);
          console.log('cashTotal :>> ', cashTotal);
          console.log('bankTotal :>> ', bankTotal);
          console.log('retainedAmount :>> ', retainedAmount);
          console.log('deductAmountTotal :>> ', deductAmountTotal);
          this.$nextTick(()=>{
            this.form.setFieldsValue({ 
              invoiceTotal:invoiceTotal,
              cashTotal:cashTotal,
              bankTotal:bankTotal,
              retainedAmount:retainedAmount,
              deductAmountTotal:deductAmountTotal
             })
          })
      },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.initSupplier()
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark',
                  'totalPrice', 'changeAmount'))
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initRetail()
        this.initPerson()
        this.initDetailAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectSup({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      onChange(event){
        console.log(event);
        console.log('999 :>> ', 999);
        console.log('this.accountTable.dataSource :>> ', this.accountTable.dataSource);
        const table = this.$refs[this.refKeys[0]]
        
        const { type, row, column, value, target } = event
        switch (column.key) {
          case 'ttl':
          case 'boxAmount':
          table.getValues((err, values) => {
            this.countTotal(values)
            this.updataForm(values)
            console.log('row :>> ', row);
            target.setValues([
              {
                rowKey: row.id,
                values: { deductAmount: +row.readingTotal - +row.boxAmount }
              }
            ])
          })
          break;
        }
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        // 设置第一个租户的total
        this.totalTable.dataSource.forEach(val=>{
          let index = detailArr.findIndex(v=>v.lessee === val.lessee)
          detailArr[index].totalAmount = val.totalAmount+''
        })
        detailArr.forEach(v=>{
          delete v.id
          delete v.tenantId
        })
        billMain.number = billMain.billNo
        billMain.operTime = billMain.billTime
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}

.total__table{
  width: 30%;
  margin: 20px 0 20px 0;
}
::v-deep .total__table .ant-table-thead tr th {
  text-align: center;
  background: #beddf9;
}
</style>